
package com.xcity.game.currency;

import com.xcity.game.common.LogCause;
import com.xcity.game.io.DeserializeStream;
import com.xcity.game.io.SerializeStream;
import com.xcity.pomelo.push.sync.LongSync;

public class LongCurrency extends AbstractCurrency {

	protected long value;
	
	public LongCurrency(CurrencyType type, short syncId, String valueAddLogFormat, String valueDecLogFormat, DeserializeStream stream) {
		super(type, syncId, valueAddLogFormat, valueDecLogFormat);
		this.value = stream != null ? stream.readLong() : 0L;
	}

	@Override
	public boolean addValue(int val, String cause) {
		return addValue((long) val, cause);
	}

	@Override
	public boolean addValue(int val, LogCause cause) {
		return addValue((long) val, cause);
	}

	@Override
	public boolean decValue(int val, String cause) {
		return decValue((long) val, cause);
	}

	@Override
	public boolean decValue(int val, LogCause cause) {
		return decValue((long) val, cause);
	}

	@Override
	public int getIntValue() {
		return (int) getLongValue();
	}

	/////////////////////////////////////////////////
	@Override
	public boolean addValue(long val, String cause) {
		return doAdd(val, cause, null);
	}
	
	@Override
	public boolean addValue(long val, LogCause cause) {
		return doAdd(val, cause != null ? cause.toString() : null, cause);
	}
	
	protected boolean doAdd(long val, String causeStr, LogCause causeObj) {
		long oldVal = this.value;
		if (val <= 0 || oldVal + val <= 0) {
			return false;
		}
		this.value += val;
		// sync to client
		short syncId = getSyncId();
		if (syncId > 0 && owner.isOnline()) {
			owner.send(new LongSync(syncId, this.value, causeObj));
		}
		// record log
		String format = getValueAddLogFormat();
		if (format != null) {
			LOG.info(format, owner.getId(), oldVal, this.value, causeStr);
		}
		return true;
	}
	
	@Override
	public boolean decValue(long val, String cause) {
		return doDec(val, cause, null);
	}
	
	@Override
	public boolean decValue(long val, LogCause cause) {
		return doDec(val, cause != null ? cause.toString() : null, cause);
	}
	
	protected boolean doDec(long val, String causeStr, LogCause causeObj) {
		long oldVal = this.value;
		if (val <= 0 || val > oldVal) {
			return false;
		}
		this.value -= val;
		// sync to client
		short syncId = getSyncId();
		if (syncId > 0 && owner.isOnline()) {
			owner.send(new LongSync(syncId, this.value, causeObj));
		}
		// record log
		String format = getValueDecLogFormat();
		if (format != null) {
			LOG.info(format, owner.getId(), oldVal, this.value, causeStr);
		}
		return true;
	}
	
	@Override
	public long getLongValue() {
		return value;
	}

	@Override
	public void write(SerializeStream out) {
		out.writeLong(value);
	}
	/////////////////////////////////////////////////

}
